var PATH_PREFIX ="";
var prdSellChannelPath="";

function setPathPrefix(path){
	PATH_PREFIX =  path;
}
function setSellChannelPath(path){
	prdSellChannelPath =  path;
}
var $disChannelList,$disChannelGridparents,$accountList,$accountGridparents,$feeList,$feeListGridparents;//基于哪个父级元素使jqgrid自适应宽度，主要解决tab标签切换隐藏的列表宽度不对的问题
function queryList() {
	
	//账户列表
	$accountList = $('#accountList');
	$accountList.jqGrid({   
		caption:'账户列表',
		url:PATH_PREFIX+'accountListPage.do',
		datatype: "json",
		colNames:["账户ID","账户层级","账户类型","开户行","开户名",'账号'],
		colModel:[  { name: 'accId',hidden : true, index: 'accType', width: 30,key: true, resizable: true, sortable: false},
					{ name: 'accLevel', index: 'accLevel',hidden : true},
		            { name: 'accTypeName', index: 'accTypeName', width: 30, resizable: true, sortable: false},
		            { name: 'accBankName', index: 'accBankName', width: 30, resizable: true, sortable: false },
		            { name: 'accName', index: 'accName', width: 30, resizable: true, sortable: false },
		            { name: 'accCode', index: 'accCode', width: 30, resizable: true, sortable: false }/*,
		            { name: 'option', index: 'option', width: 30, resizable: true, sortable: false}*/
				  ],
		rowNum: 20,
        rowList: [20, 30, 50],
        rownumbers: true,
        rownumWidth: 50,
        prmNames: { search: "search", page: "pageNo", rows: "limit" },
        height: 'auto',
        width: false,
        autowidth:true,
        editurl: '',
        viewrecords: true,
        cellEdit: false,
        shrinkToFit: true,
        grouping: false,
        postData:{
        	'sp[prjcode]':$("#prjcode").val()
    	},
        jsonReader: {
            root: "items", //结果集
            records: "total", //总记录数 
            total: "pageCount", //总页数
            page: "pageNo", //当前页 
            repeatitems: false // (4) 
        },  
		multiselect:true,
		pager: "#accountListPage",					
		viewrecords: true,
		hidegrid: false, 
		gridComplete: function(){
			var ids = $accountList.jqGrid('getDataIDs');
			for(var i=0;i < ids.length;i++){
				var rowId = ids[i];
				var params = {
						'detail' : 'productDetailTemple'
					};
				var permissionButton = Permission_Button.configPermissionButton(params);
				permissionButton.detail = "查看";
                $accountList.jqGrid('setRowData', ids[i], { option: Permission_Button.linkAllBtn(permissionButton)});
			}	
		}
	});
	
	$accountList.navGrid('#accountListPage',{edit:false,add:false,del:false,search:false,refreshstate:'current'}).navButtonAdd("#accountListPage",{  
		id: "accountList_btnAdd",
		caption:"新增",   
		buttonicon:"ui-icon-plus",  
		position:"last", 
		onClickButton: function(){
			accountListAdd($("#prjcode").val());
		},
		}).navButtonAdd("#accountListPage",{  
			id: "accountList_btnDel",
			caption:"删除",   
			buttonicon:"ui-icon-trash",  
			position:"last", 
			onClickButton: function(){
				accountListDel();
			},
		});
	$accountList.jqGrid('setFrozenColumns');
	jqGridResize($accountList);
	
};

function accountListAdd(prjcode){
	layer.open({
		  title: '新增账户列表',
	      type: 2,
	      area: ['800px', '380px'], // 设置宽度，高度
	      shadeClose: true, //点击遮罩关闭
	      content: [encodeURI(PATH_PREFIX+"/prdAccountListAdd.do?prjcode="+prjcode),'no'],//no代表不显示滚动条
	      isOutAnim: false,
	      resize: false,
	      end: function(){ 
	    	  queryPrdAccountListByCondition();
	    	 }
	    });
}

function accountListDel(){
	var ids =  $("#accountList").jqGrid('getGridParam', 'selarrrow');//选择多选
	if(undefined != ids && ids.length > 0){
		ctools.confirm({text:"是否确认删除当前账户信息？"},function(isConfirm){
			if(isConfirm){
				if (ids == null || ids == "") {
					return;
				}
				$.ajax({
					type: 'POST',
					url: PATH_PREFIX + "/prdAccountListDel.do",
					dataType:'json',
					data:{
						"accIds" : ids.join(",")
					},
					success: function(data){
						ctools.alert_sweet(data.message, "success", "" , function(){
							queryPrdAccountListByCondition();
						});
					},
					error:function(xhr){
						switch(xhr.status){
							case 403:sweetAlert("对不起，您无此权限！","","error");break;
							case 404:sweetAlert("对不起，无此页面！", "","error");break;
							case 500:sweetAlert("内部错误，请联系管理员！","","error");break;  
							case 504:sweetAlert("超时，请联系管理员！", "","error");break;  
							case 417:sweetAlert("内部错误，请联系管理员！", "","error");break;  
						}
					}
				});
			}
		});
	}else{
		toastr.warning('', '请勾选需要删除的账户信息');
		return false;
	}
}

function initPage(){
	removeActive();
	$(".progress-icon").each(function(index,obj){
		if(index < $("#prjprcstat").val()){
			$(obj).addClass("active");
		}
	});
	//页签
	$("#singleDemand_li").addClass("active");
	//页面
	$('#singleProductDemand').hide();
	$('#singleProductDetail').show();
}

function showTitle(text, options, rData){
	var channelId = rData["channelId"];
	if(channelId==null || channelId == ''){
		return "";
	}
	if("0" == text){
		text = "否"
	}else if("1" == text){
		text = "是"
	}
	return text;
}

function dateFormatter(text, options, rData){
	if(text == null){
		return "";
	}
	return moment(text).format('YYYY-MM-DD');
}

// 概览
function showDemand(){
	initPage();
}

function queryPrdAccountListByCondition(subPrdCode) {
	var postData = $("#accountList").jqGrid("getGridParam", "postData");
    $.extend(postData,{
        'sp[prjcode]':$("#prjcode").val()
    });
    $("#accountList").jqGrid('setGridParam',{"datatype": "json"}).trigger("reloadGrid",[{page:1}]);//重新载入Grid表格
}

//详情
function showList(){
	removeActive();
	//页签
	$("#singleList_li").addClass("active");
	//页面
	$('#singleProductDemand').hide();
	$('#singleProductDetail').show();
	queryList();
	var subPrdCode = $("#subPrdCode").val();
	if (subPrdCode) {
		feeYieldList();
		prdSellChannelList(subPrdCode);
		querySubPrdInfo(subPrdCode);
	}
	$("#sub_" + subPrdCode).addClass("active");
}


function removeActive(){
	$("#singleDemand_li").removeClass("active");
	$("#singleList_li").removeClass("active");
}

function dialogNavPage(){
	var actionUrl =  "/solution/business/customerEquity/navInfo/navInfoView.do?prjcode="+$("#prjcode").val();
	window.open(actionUrl);
}

function querySubPrdInfo(subPrdCode) {
	$.ajax({
		url: PATH_PREFIX + "querySubPrdInfoBySubPrdCode.do",
		type: "POST",
		data: {subPrdCode: subPrdCode},
		dataType: "JSON",
		success: function (data) {
			if (data.success) {
				var newsTemplate = $("#newsTemplate").html()
									.replace(/{{currencyTypeNm}}/g, data.object.currencyTypeNm)
									.replace(/{{redemptionRule}}/g, data.object.redemptionRule==null?'':data.object.redemptionRule)
									.replace(/{{initParValue}}/g, data.object.initParValue==null?'':data.object.initParValue)
									.replace(/{{intModeNm}}/g, data.object.intModeNm)
									.replace(/{{isBeforePayFeeNm}}/g, data.object.isBeforePayFeeNm)
									.replace(/{{indBookStart}}/g, data.object.indBookStart==null?'':data.object.indBookStart)
									.replace(/{{insBookStart}}/g, data.object.insBookStart==null?'':data.object.insBookStart)
									.replace(/{{bookStep}}/g, data.object.bookStep==null?'':data.object.bookStep)
									.replace(/{{bookFeeRate}}/g, data.object.bookFeeRate==null?'':data.object.bookFeeRate)
									.replace(/{{indDeclareStart}}/g, data.object.indDeclareStart==null?'':data.object.indDeclareStart)
									.replace(/{{insDeclareStart}}/g, data.object.insDeclareStart==null?'':data.object.insDeclareStart)
									.replace(/{{declareFeeRate}}/g, data.object.declareFeeRate==null?'':data.object.declareFeeRate)
									.replace(/{{applyStep}}/g, data.object.applyStep==null?'':data.object.applyStep)
									.replace(/{{redeemFeeRate}}/g, data.object.redeemFeeRate==null?'':data.object.redeemFeeRate)
									.replace(/{{breachFeeRate}}/g, data.object.breachFeeRate==null?'':data.object.breachFeeRate);
				
				$("#subDetailDiv").html(newsTemplate);	
				$("#subPrdCode").val(data.object.subPrdCode);
				queryPrdSellChannelByCondition(data.object.subPrdCode);
				queryByCondtion(true, data.object.subPrdCode);
			}
		},
		error: function () {}
	})
}


